package com.luolc.instantmessager.home;
/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2016-2017 Luolc
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

import android.Manifest;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.util.Log;

import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.easeui.EaseUI;
import com.luolc.instantmessager.base.BaseActivity;
import com.luolc.instantmessager.home.conversation.ConversationListFragment;
import com.luolc.instantmessager.permission.PermissionsManager;
import com.luolc.instantmessager.permission.PermissionsResultAction;
import com.luolc.instantmessager.util.UiUtils;

import java.util.List;

public class HomeActivity extends BaseActivity {
  private static final String TAG = HomeActivity.class.getSimpleName();

  private ConversationListFragment conversationListFragment;

  private EMMessageListener messageListener = new EMMessageListener() {
    @Override
    public void onMessageReceived(List<EMMessage> messages) {
      for (EMMessage message : messages) {
        EaseUI.getInstance().getNotifier().onNewMsg(message);
      }
      refreshUiWithNewMessage();
    }

    @Override
    public void onCmdMessageReceived(List<EMMessage> list) {
    }

    @Override
    public void onMessageRead(List<EMMessage> list) {
    }

    @Override
    public void onMessageDelivered(List<EMMessage> list) {
    }

    @Override
    public void onMessageRecalled(List<EMMessage> list) {
    }

    @Override
    public void onMessageChanged(EMMessage emMessage, Object o) {
    }
  };

  private void refreshUiWithNewMessage() {
    runOnUiThread(() -> {
      if (conversationListFragment != null) {
        conversationListFragment.refresh();
      }
    });
  }

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestPermissions();
    if (savedInstanceState == null
        || getSupportFragmentManager().findFragmentByTag("fragment") == null) {
      conversationListFragment = new ConversationListFragment();
      getSupportFragmentManager()
          .beginTransaction()
          .add(android.R.id.content, conversationListFragment, "fragment")
          .commit();
    }
  }

  @Override
  protected void onResume() {
    super.onResume();
    EMClient.getInstance().chatManager().addMessageListener(messageListener);
  }

  @Override
  protected void onStop() {
    super.onStop();
    EMClient.getInstance().chatManager().removeMessageListener(messageListener);
  }

  private void requestPermissions() {
    final String[] permissions = {
        Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE
    };
    PermissionsManager.getInstance().requestPermissionsIfNecessaryForResult(this, permissions,
        new PermissionsResultAction() {
          @Override
          public void onGranted() {
            Log.d(TAG, "已允许");
          }

          @Override
          public void onDenied(String permission) {
            Log.d(TAG, "已禁止" + permission);
            UiUtils.toast(HomeActivity.this, "禁止以上权限可能导致无法正常使用本软件");
          }
        });
  }

  @Override
  public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                         @NonNull int[] grantResults) {
    PermissionsManager.getInstance().notifyPermissionsChange(permissions, grantResults);
  }
}
